const fs = require('fs');
const path = require('path');
const { app } = require('electron');

/**
 * AnalysisReportService
 * 负责管理分析报告的本地文件存储
 * Path: userData/analysis_reports/{caseId}/{subjectId}/report.json
 */
class AnalysisReportService {
    constructor() {
        this.baseDir = path.join(app.getPath('userData'), 'analysis_reports');
        this.ensureBaseDir();
    }

    ensureBaseDir() {
        if (!fs.existsSync(this.baseDir)) {
            fs.mkdirSync(this.baseDir, { recursive: true });
        }
    }

    getReportDir(caseId, subjectId) {
        // subjectId 为 null 或 'global' 时表示全量分析
        const safeSubjectId = subjectId || 'global';
        const dir = path.join(this.baseDir, caseId, safeSubjectId);
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
        return dir;
    }

    /**
     * 保存分析报告
     * @param {string} caseId 
     * @param {string} subjectId 
     * @param {Object} reportData 
     */
    async saveReport(caseId, subjectId, reportData) {
        try {
            const dir = this.getReportDir(caseId, subjectId);

            // 需求：重新生成的时候会删除旧的报告
            // 这里简单处理：直接覆盖 report.json，或者删除该目录下所有 json
            const files = fs.readdirSync(dir);
            for (const file of files) {
                if (file.endsWith('.json')) {
                    fs.unlinkSync(path.join(dir, file));
                }
            }

            const filename = `report_${Date.now()}.json`;
            const filePath = path.join(dir, filename);

            fs.writeFileSync(filePath, JSON.stringify(reportData, null, 2), 'utf-8');
            console.log(`[AnalysisReportService] Saved report to ${filePath}`);
            return { success: true, path: filePath };
        } catch (error) {
            console.error('[AnalysisReportService] Save failed:', error);
            throw error;
        }
    }

    /**
     * 加载最新报告
     * @param {string} caseId 
     * @param {string} subjectId 
     */
    async loadReport(caseId, subjectId) {
        try {
            const dir = this.getReportDir(caseId, subjectId);
            const files = fs.readdirSync(dir)
                .filter(f => f.endsWith('.json'))
                .sort()
                .reverse(); // 最新日期在前 (假设文件名包含时间戳或按字母序)

            if (files.length === 0) return null;

            const filePath = path.join(dir, files[0]);
            const content = fs.readFileSync(filePath, 'utf-8');
            return JSON.parse(content);
        } catch (error) {
            console.error('[AnalysisReportService] Load failed:', error);
            return null;
        }
    }

    /**
     * 删除报告
     */
    async deleteReport(caseId, subjectId) {
        try {
            const dir = this.getReportDir(caseId, subjectId);
            fs.rmdirSync(dir, { recursive: true });
            return true;
        } catch (error) {
            console.error('[AnalysisReportService] Delete failed:', error);
            return false;
        }
    }
}

module.exports = new AnalysisReportService();
